package top.xiaodaiyu.shiro.auth.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.CachingSessionDAO;
import org.springframework.util.SerializationUtils;
import redis.clients.jedis.Jedis;

import java.io.Serializable;

/**
 * @author by  Administrator
 * 包名空间  top.xiaodaiyu.shiro.auth.config
 * 用途
 * Created by dtt on 2018/8/2
 * Email 532199946@qq.com
 **/
@Slf4j
public class RedisSessionDao extends CachingSessionDAO {
    private static final String PREFIX = "SHIRO_SESSION_ID";

    private static final int EXPRIE = 10000;

    private byte[] getByteKey(Object k){
        if(k instanceof String){
            String key = PREFIX+k;
            return key.getBytes();
        }else {
            return SerializationUtils.serialize((Serializable) k);
        }
    }

   @Override
    protected void doUpdate(Session session) {
       log.info("========更新session===========");
       if(session==null){
           return;
       }
       Jedis jedis = JedisUtil.getJedis();
       session.setTimeout(EXPRIE*100);

       jedis.setex(getByteKey(session.getId()),EXPRIE,SerializationUtils.serialize((Serializable)session) );

    }

    @Override
    protected void doDelete(Session session) {
        log.info("========删除session==========");
        Jedis jedis = JedisUtil.getJedis();
        jedis.del(getByteKey(session.getId()));
        JedisUtil.closeJedis(jedis);
    }

    @Override
    protected Serializable doCreate(Session session) {
        log.info("========开始创建session==========");
        Serializable serializable = this.generateSessionId(session);
        session.setTimeout(EXPRIE*1000);
        Jedis jedis = JedisUtil.getJedis();
        assignSessionId(session,serializable);
        jedis.setex(getByteKey((String)serializable),EXPRIE, SerializationUtils.serialize((Serializable)session) );
        JedisUtil.closeJedis(jedis);
        return serializable;
    }

    @Override
    protected Session doReadSession(Serializable serializable) {
        log.info("==========开始读session==============");
        Jedis jedis = JedisUtil.getJedis();
        Session session = null;
        byte[] s = jedis.get(getByteKey(serializable));
        if(s!=null){
            session = (Session) SerializationUtils.deserialize(s);
            jedis.expire((PREFIX+serializable).getBytes(),EXPRIE);
        }
        if(session==null){
            return null;
        }
        return session;
    }
}
